package com.sita.tboard.roadtrust.discovery;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.danikula.videocache.CacheListener;
import com.danikula.videocache.HttpProxyCacheServer;
import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.sita.bike.R;
import com.sita.bike.persistence.RtResourceEntityDao;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.LocalStorage;
import com.sita.tboard.global.LocalConstants;
import com.sita.tboard.roadtrust.event.RtResourceRefreshEvent;
import com.sita.tboard.roadtrust.helper.RtResourceNetworkHelper;
import com.sita.tboard.ui.tools.L;
import com.sita.tboard.view.MyDividerItemDecoration;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

/**
 * Created by xiaodong on 16/3/22.
 */
public class RtResourceListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>,
        SwipeRefreshLayout.OnRefreshListener,
        OnMoreListener {
    @Bind(R.id.resource_list)
    SuperRecyclerView resourceListView;

    private LinearLayoutManager mLinearLayoutManager;
    private LoaderManager.LoaderCallbacks loaderCallbacks;
    private RtResourceListAdapter mAdapter;

    private final int pageSize = 15;

    private int currPage = 0;

    private String authorId = "";

    private static class MyCursorLoader extends CursorLoader {

        // support select for defined the resource by some
        private String accountId = "";

        public MyCursorLoader(Context context) {
            super(context);

        }

        public MyCursorLoader(Context context, String accountId) {
            super(context);
            this.accountId = accountId;
        }

        public Cursor loadInBackground() {
            SQLiteDatabase db = GlobalContext.getDaoSession().getDatabase();
            String whereClause = (TextUtils.isEmpty(accountId)) ? null : RtResourceEntityDao.Properties.AccountId.columnName + "=?";
            String[] whereArgs = (TextUtils.isEmpty(accountId)) ? null : new String[]{String.valueOf(accountId)};
            return db.query(RtResourceEntityDao.TABLENAME, null, whereClause, whereArgs, null, null, RtResourceEntityDao.Properties.CreateDate.columnName + " desc");
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new MyCursorLoader(GlobalContext.getGlobalContext(), authorId);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        if (mAdapter == null) {
            mAdapter = new RtResourceListAdapter(getContext(), cursor);
            resourceListView.setAdapter(mAdapter);
        } else {
            mAdapter.swapCursor(cursor);
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_rt_resource_list, null);
        ButterKnife.bind(this, v);
        resourceListView.setLayoutManager(new LinearLayoutManager(getActivity()));

        Drawable drawable = new ColorDrawable(getResources().getColor(R.color.divider_list));
        resourceListView.addItemDecoration(new MyDividerItemDecoration(drawable, true, true));

        resourceListView.setOnMoreListener(this);
        resourceListView.setRefreshListener(this);
        getAuthorId();

        return v;
    }

    private void getAuthorId() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            authorId = bundle.getString(Constants.BUNDLE_ARGUMENT_AUTHOR_ID);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (getLoaderManager().getLoader(LocalConstants.RT_RESOURCE_LOADER) == null) {
            getLoaderManager().initLoader(LocalConstants.RT_RESOURCE_LOADER, null, this);
        } else {
            getLoaderManager().restartLoader(LocalConstants.RT_RESOURCE_LOADER, null, this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        if ((mAdapter != null && mAdapter.getItemCount() == 0) || currPage == 0) {
            requestData();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //JCVideoPlayer.releaseAllVideos();
    }

    // when load more
    @Override
    public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
        L.i("onMoreAsked");
        currPage += 1;
        requestData();
    }

    // when refresh
    @Override
    public void onRefresh() {
        L.i("onRefresh");

        currPage = 0;
        requestData();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    private void requestData() {
        if (currPage == 0) {
            long startTime = LocalStorage.getRtRefreshTime();
            long endTime = System.currentTimeMillis();
            RtResourceNetworkHelper.getInstance(authorId).getResourceList(pageSize, currPage, startTime, endTime);
        } else {
            long endTime = LocalStorage.getRtRefreshTime();
            RtResourceNetworkHelper.getInstance(authorId).getResourceList(pageSize, currPage, null, endTime);
        }
    }

    public void onEventMainThread(RtResourceRefreshEvent event) {
        switch (event.getMode()) {
            case REFRESH: {
                resourceListView.setRefreshing(false);
                if (!event.getHasData()) {
                    currPage = 0;
                }
            }
            case MORE: {
                resourceListView.hideMoreProgress();
                if (!event.getHasData()) {
                    currPage -= 1;
                }
            }
        }
        getActivity().getSupportLoaderManager().restartLoader(LocalConstants.RT_RESOURCE_LOADER, null, this);
    }
}
